<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科研项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入关联的科研项目ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成果类型" prop="outcomeType">
        <el-select v-model="queryParams.outcomeType" placeholder="请选择成果类型" clearable>
          <el-option
            v-for="dict in dict.type.out_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成果标题或名称" prop="outcomeTitle">
        <el-input
          v-model="queryParams.outcomeTitle"
          placeholder="请输入成果标题或名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成果完成日期" prop="outcomeDate">
        <el-date-picker clearable
          v-model="queryParams.outcomeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择成果完成日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="成果转化状态" prop="outcomeStatus">
        <el-select v-model="queryParams.outcomeStatus" placeholder="请选择成果转化状态" clearable>
          <el-option
            v-for="dict in dict.type.out_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['outcome:outcome:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['outcome:outcome:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['outcome:outcome:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['outcome:outcome:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="outcomeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="成果ID" align="center" prop="outcomeId" />
      <el-table-column label="科研项目ID" align="center" prop="projectId" />
      <el-table-column label="科研项目名称" align="center" prop="projectName" />
      <el-table-column label="图片" align="center" width="200">
        <template slot-scope="scope">
        <img
       :src="scope.row.picture"
       alt="产品图片"
       style="width: 80%; height: auto; max-height: 200px; object-fit: cover;"
       />
       </template>
    </el-table-column>
      <el-table-column label="成果类型" align="center" prop="outcomeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.out_type" :value="scope.row.outcomeType"/>
        </template>
      </el-table-column>
      <el-table-column label="成果名称" align="center" prop="outcomeTitle" />
      <el-table-column label="成果描述" align="center" prop="outcomeDescription" />
      <el-table-column label="成果完成日期" align="center" prop="outcomeDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outcomeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成果转化状态" align="center" prop="outcomeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.out_status" :value="scope.row.outcomeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['outcome:outcome:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['outcome:outcome:remove']"
          >删除</el-button>
          <el-button
           size="mini"
           type="text"
           icon="el-icon-document"
           @click="fetchOutcomeTrackData(scope.row.outcomeId)"
         >查看变更记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="追踪记录" :visible.sync="trackDialogVisible" width="800px" append-to-body>
      <el-table :data="trackList" size="small" v-loading="trackLoading" @selection-change="handleSelectionChanges">
        <el-table-column type="selection" width="55" align="center" />
    <el-table-column prop="trackId" label="记录ID" align="center" />
    <el-table-column prop="actionType" label="操作类型" align="center">
      <template slot-scope="scope">
        <el-tag type="info" v-if="scope.row.actionType === 'add'">新增</el-tag>
        <el-tag type="success" v-else-if="scope.row.actionType === 'update'">修改</el-tag>
        <el-tag type="danger" v-else>删除</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="outcomeType" label="成果类型" align="center">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.out_type" :value="scope.row.outcomeType" />
      </template>
    </el-table-column>
    <el-table-column prop="outcomeTitle" label="成果标题" align="center" />
    <el-table-column prop="outcomeDate" label="完成日期" align="center" />
    <el-table-column prop="outcomeStatus" label="转化状态" align="center">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.out_status" :value="scope.row.outcomeStatus" />
      </template>
    </el-table-column>
    <el-table-column prop="createdBy" label="创建人" align="center" />
    <el-table-column prop="createdAt" label="创建时间" align="center" />
    <el-table-column prop="updatedAt" label="更新时间" align="center" />
    <el-table-column prop="updatedBy" label="更新人" align="center" />
    <el-table-column prop="deletedAt" label="删除时间" align="center" />
    <el-table-column prop="isDeleted" label="删除标记" align="center">
      <template slot-scope="scope">
        <el-tag type="info" v-if="scope.row.isDeleted === 0">否</el-tag>
        <el-tag type="danger" v-else>是</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="version" label="版本号" align="center" />

  </el-table>
  <div slot="footer" class="dialog-footer">
    <el-button @click="trackDialogVisible = false">关闭</el-button>
    <el-button type="primary" @click="revertToSelectedRecord">回溯到此记录</el-button>
</div>
</el-dialog>


    <!-- 添加或修改科研项目成果对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联的科研项目ID" prop="projectId">
          <el-input v-model="form.projectId" placeholder="请输入关联的科研项目ID" />
        </el-form-item>
        <el-form-item label="成果类型" prop="outcomeType">
          <el-select v-model="form.outcomeType" placeholder="请选择成果类型">
            <el-option
              v-for="dict in dict.type.out_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成果标题或名称" prop="outcomeTitle">
          <el-input v-model="form.outcomeTitle" placeholder="请输入成果标题或名称" />
        </el-form-item>
        <el-form-item label="成果描述" prop="outcomeDescription">
          <el-input v-model="form.outcomeDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="成果完成日期" prop="outcomeDate">
          <el-date-picker clearable
            v-model="form.outcomeDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择成果完成日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="成果转化状态" prop="outcomeStatus">
          <el-select v-model="form.outcomeStatus" placeholder="请选择成果转化状态">
            <el-option
              v-for="dict in dict.type.out_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <div class="text-center">
         上传图片：   <userAvatar />
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutcome, getOutcome, delOutcome, addOutcome, updateOutcome,getOutcomeTrack } from "@/api/outcome/outcome";
import userAvatar from './userAvatar.vue';
import store from "@/store";
export default {
  name: "Outcome",
  dicts: ['out_type', 'out_status'],

  components: { userAvatar },

  data() {
    return {
      selectedTrack: null, // 存储选中的追踪记录
      // 追踪记录弹窗控制
      trackDialogVisible: false,
     // 追踪记录数据
      trackList: [],
      // 追踪记录加载状态
      trackLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研项目成果表格数据
      outcomeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        outcomeType: null,
        outcomeTitle: null,
        outcomeDescription: null,
        outcomeDate: null,
        outcomeStatus: null,
        picture: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "关联的科研项目ID不能为空", trigger: "blur" }
        ],
        outcomeType: [
          { required: true, message: "成果类型不能为空", trigger: "change" }
        ],
        outcomeTitle: [
          { required: true, message: "成果标题或名称不能为空", trigger: "blur" }
        ],
        outcomeDate: [
          { required: true, message: "成果完成日期不能为空", trigger: "blur" }
        ],
        outcomeStatus: [
          { required: true, message: "成果转化状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听 Vuex 中 avatar 的变化，更新 imgUrl
    '$store.getters.avatar': function(newAvatar) {
     this.form.picture = newAvatar;
    }
  },
  methods: {
    /** 查询科研项目成果列表 */
    getList() {
      this.loading = true;
      listOutcome(this.queryParams).then(response => {
        this.outcomeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        outcomeId: null,
        projectId: null,
        outcomeType: null,
        outcomeTitle: null,
        outcomeDescription: null,
        outcomeDate: null,
        outcomeStatus: null,
        createdBy: null,
        updatedBy: null,
        deletedBy: null,
        deletedAt: null,
        isDeleted: null,
        version: null,
        createdAt: null,
        updatedAt: null,
        picture: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.outcomeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加科研项目成果";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const outcomeId = row.outcomeId || this.ids
      getOutcome(outcomeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改科研项目成果";
        store.commit('SET_AVATAR', this.form.picture);

        console.log(store.getters.avatar )
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.outcomeId != null) {
            updateOutcome(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutcome(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const outcomeIds = row.outcomeId || this.ids;
      this.$modal.confirm('是否确认删除科研项目成果编号为"' + outcomeIds + '"的数据项？').then(function() {
        return delOutcome(outcomeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('outcome/outcome/export', {
        ...this.queryParams
      }, `outcome_${new Date().getTime()}.xlsx`)
    },

    fetchOutcomeTrackData(outcomeId) {
      console.log("Fetching data for outcomeId:", outcomeId);
      this.trackDialogVisible = true;
      this.trackList = [];
      this.trackLoading = true;
      getOutcomeTrack(outcomeId)
        .then(response => {
          console.log("Response data:", response.data);
          this.trackList = response.data || [];
          console.log("数据"+this.trackList);
        })
        .catch(error => {
          this.$message.error('获取追踪记录失败');
          console.error(error);
        })
        .finally(() => {
          this.trackLoading = false;
        });
    },
    handleSelectionChanges(selection) {
        this.selectedTrack = selection.length > 0 ? selection[0] : null; // 选择第一条记录
    },
    revertToSelectedRecord() {
        if (!this.selectedTrack) {
            this.$message.warning('请先选择一条记录进行回溯');
            return;
        }
        // 这里可以实现回溯逻辑，比如调用 API 更新原表数据
        const updatedData = {
            // 根据 selectedTrack 的内容构建更新的数据
            ...this.selectedTrack,
            // 例如，您可能想要清除一些字段或者修改某些字段
        };
        updateOutcome(updatedData) // 假设这是更新原表的 API
            .then(response => {
                this.$message.success('数据回溯成功');
                // 可能需要重新获取原表数据
                this.getList();
            })
            .catch(error => {
                this.$message.error('数据回溯失败');
                console.error(error);
            });
    }

  }
};
</script>
